// Declenchement sur Interruption Externe
#ifdef __USE_CMSIS
#include "LPC17xx.h"
#endif
#include <cr_section_macros.h>
#include <NXP/crp.h>

// Variable to store CRP value in. Will be placed automatically
// by the linker when "Enable Code Read Protect" selected.
// See crp.h header for more information
__CRP const unsigned int CRP_WORD = CRP_NO_CRP ;

#include <stdio.h>

volatile int pulse, mesure_f, compteur = 0, diff = 0, timer0_counter = 0;
void EINT0_IRQHandler(void);
void TIMER0_IRQHandler (void); // Timer pour mesure de la frequence
void config_timer0(void);
void config_pins(void);
int main(void)
{
	int i = 0;
	printf("Declenchement sur Int. Externe sur P2.10\n");
	
	pulse = 0;
	mesure_f = 0;

	config_pins();
	config_timer0();
	NVIC_EnableIRQ(TIMER0_IRQn);

	LPC_TIM0->PR = 0;   // Prescaler = 0
	LPC_TIM0->MR0 = 0;
	LPC_TIM0->MCR = 0; // pas d'Int., juste RAZ TC
    LPC_TIM0->TCR = (1<<0); // demarre Timer0

	while(1)
	{
	  for(i=0; i < 15000000; i++);

		printf("pulses = %d, compteur = %d, diff = %d\n", pulse, compteur ,diff);
	}
	return 0 ;
}

void config_pins(void)
{
// Set PINSEL4 [21:20] function "01" for P2.10 as EINT0
 LPC_PINCON->PINSEL4 &= ~(0x11 << 20);
 LPC_PINCON->PINSEL4 |= (0x01 << 20);
 LPC_SC->EXTMODE |= 1<<0; // edge sensitive
 LPC_SC->EXTPOLAR |= 1<<0; // rising edge
 NVIC_EnableIRQ(EINT0_IRQn);
}

void config_timer0()
{
	LPC_SC->PCONP |= (1<<1);  // Timer0 ON
	LPC_SC->PCLKSEL0 &= ~(1<<3);
	LPC_SC->PCLKSEL0 |= (1<<2);  // Timer0 clock = CCLK
	//LPC_TIM0->PR = 0; // Prescaler
}

void EINT0_IRQHandler(void)
{
  LPC_SC->EXTINT = (1<<0); // RAZ Int.
  pulse++;
  diff = LPC_TIM0->TC - compteur;
  compteur = LPC_TIM0->TC;
  LPC_TIM0->TCR = 2; // RESET Timer0
  LPC_TIM0->TCR = 1; // ON
}

void TIMER0_IRQHandler (void)
{
  LPC_TIM0->IR = 1; // RAZ
  timer0_counter++;
}

